﻿using Ivony.Html;
using Ivony.Html.Parser;
using RestSharp;
using System;
using System.IO;
using YouWei.Utility;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Linq;
using YouWei.Infrastructure.Models;

namespace YouWei.Console
{
    public class carImg
    {
        public void excute()
        {
            Uri u = new Uri("http://car.bitauto.com/");
            RestClient client = new RestClient("http://car.bitauto.com/");
            var request = new RestRequest("", Method.GET);
            IRestResponse response = client.Execute(request);
            var content = response.Content;
            IHtmlDocument source = new JumonyParser().Parse(content);
            var imageDoms = source.Find("#letter2 span ").Find(".logo-img").Find("img");
            if (imageDoms != null)
            {
                foreach (var item in imageDoms)
                {
                    var srcDom = item.Attribute("src");
                    if (srcDom == null)
                        srcDom = item.Attribute("data-src");
                    if (srcDom == null)
                        continue;
                    string src = srcDom.AttributeValue;
                    if (!string.IsNullOrWhiteSpace(src))
                    {
                        string filePath = "C://carimg";
                        string dir = Path.GetDirectoryName(filePath);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        if (Path.GetExtension(src) == ".jpg")
                            return;
                        //替换掉//res.wx.qq.com/mmbizwap的//
                        var imageName = src;
                        imageName = Regex.Replace(imageName, "http://image.bitautoimg.com/bt/car/default/images/logo/masterbrand/png/100/", "");
                        var img = ImageHelper.UrlToImage(src);
                        var savePath = filePath + "//" + imageName;
                        using (Bitmap tempImage = new Bitmap(img))
                        {
                            tempImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                        }
                    }
                }
            }
        }
    }
}

